package cn.gz.demo.ui;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import cn.gz.demo.R;
import cn.gz.demo.databinding.WebSocketBinding;
import cn.gz.demo.ui.base.BaseActivity;
import cn.gz.demo.utils.LogUtil;

/**
 * @author Liuyz
 * @date 2020/6/811:33
 */
public class WebSocketActivity_1 extends BaseActivity {
    private WebSocketBinding binding;
    private JWebSocketClient mSocketClient;
    private int index = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LogUtil.showLog("............" + msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_websocket);

        initView();
        binding.send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSocketClient != null && mSocketClient.isOpen()) {
                    ++index;
                    mSocketClient.send("发送第" + index + "次");
                }
            }
        });
    }

    private void initView() {
        URI uri = URI.create("ws://192.168.30.98:10029/websocket/10000");
        mSocketClient = new JWebSocketClient(uri) {
            @Override
            public void onMessage(String message) {
                //message就是接收到的消息
                binding.receive.setText(message);
            }
        };
        try {
            mSocketClient.connectBlocking();
            mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public class JWebSocketClient extends WebSocketClient {
        public JWebSocketClient(URI serverUri) {
            super(serverUri, new Draft_6455());
        }

        @Override
        public void onOpen(ServerHandshake handshakedata) {
            LogUtil.showLog("JWebSocketClient", "onOpen()");
        }

        @Override
        public void onMessage(String message) {
            LogUtil.showLog("JWebSocketClient", "onMessage()");
        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
            LogUtil.showLog("JWebSocketClient", "onClose()");
        }

        @Override
        public void onError(Exception ex) {
            LogUtil.showLog("JWebSocketClient", "onError()");
        }
    }

    private long sendTime = 0L;
    private long HEART_BEAT_RATE = 15000;
    // 发送心跳包
    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
                if (mSocketClient != null) {
                    boolean isSuccess = mSocketClient.isClosed();
                    LogUtil.showLog(".........isSuccess..............." + isSuccess);
                    if (isSuccess) {//长连接已断开
                        mHandler.removeCallbacks(heartBeatRunnable);
                        reconnectWs();
                    } else {//长连接处于连接状态

                    }
                } else {
                    initView();
                }
                sendTime = System.currentTimeMillis();
                mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//延时100毫秒
            }
        }
    };

    /**
     * 开启重连
     */
    private void reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable);
        new Thread() {
            @Override
            public void run() {
                try {
                    //重连
                    mSocketClient.reconnectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 断开连接
     */
    private void closeConnect() {
        try {
            if (null != mSocketClient) {
                mSocketClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mSocketClient = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeConnect();
    }
}
